package com.sun.springsecruity.service;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Objects;

/**
 * @author sun
 */
@Component
public class PasswordEncoderServiceImpl implements PasswordEncoder {

    public static void main(String[] args) {
        System.out.println(new BCryptPasswordEncoder().encode("123456"));

    }

    /**
     * 密码加密
     * @param rawPassword 原始密码
     */
    @Override
    public String encode(CharSequence rawPassword) {
        return privateEncode(rawPassword);
    }

    /**
     * 密码匹配
     * @param rawPassword 原始密码
     * @param encodedPassword 加密的密码，通常从数据库中取得
     * @return 匹配结果
     */
    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        // 1.对明文密码加密
        String formPassword = privateEncode(rawPassword);
        // 2. 声明数据库密码
        String databasePassword = encodedPassword;
        // 3. 比较密码
        return Objects.equals(formPassword, databasePassword);
    }

    /**
     * 自定义加密规则
     * @param rawPassword 原始密码
     * @return 加密后的密码
     */
    private String privateEncode(CharSequence rawPassword){
        String algorithm = "MD5";
        try {
            // 1. 创建MessagDigest对象
            MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
            // 2. 获取rawPassword的字节数组
            byte[] input = ((String)rawPassword).getBytes();
            // 3. 加密
            byte[] output = messageDigest.digest(input);
            // 4. 转为16进制的对应字符
            return new BigInteger(1, output).toString(16).toUpperCase();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }
}
